const PENDING = 'pending';
const FULFILLED = 'fulfilled';
const REJECTED = 'rejected';
class MyPromise {
  constructor(executor) {
    try {
      executor(this.resolve, this.reject);
    } catch (e) {
      this.reject(e);
    }
  }
  status = PENDING;
  value = undefined;
  reason = undefined;
  successCallback = [];
  failCallback = [];
  resolve = (value) => {
    if (this.status !== PENDING) return;
    this.status = FULFILLED;
    this.value = value;
    while (this.successCallback.length) this.successCallback.shift()();
  };
  reject = (reason) => {
    if (this.status !== PENDING) return;
    this.status = REJECTED;
    this.reason = reason;
    while (this.failCallback.length) this.failCallback.shift()();
  };
  then(successCallback, failCallback) {
    successCallback = successCallback || ((value) => value);
    failCallback =
      failCallback ||
      ((reason) => {
        throw reason;
      });
    const promise = new Promise((resolve, reject) => {
      if (this.status === FULFILLED) {
        setTimeout(() => {
          try {
            let x = successCallback(this.value);
            resolvePromise(promise, x, resolve, reject);
          } catch (e) {
            reject(e);
          }
        });
      } else if (this.status === REJECTED) {
        setTimeout(() => {
          try {
            let x = failCallback(this.reason);
            resolve(promise, x, resolve, reject);
          } catch (e) {
            reject(e);
          }
        });
      } else {
        this.successCallback.push(() => {
          setTimeout(() => {
            try {
              let x = successCallback(this.value);
              resolvePromise(promise, x, resolve, reject);
            } catch (e) {
              reject(e);
            }
          });
        });
        this.failCallback.push(() => {
          setTimeout(() => {
            try {
              let x = failCallback(this.reason);
              resolvePromise(promise, x, resolve, reject);
            } catch (e) {
              reject(e);
            }
          });
        });
      }
    });
    return promise;
  }
  catch(failCallback) {
    return this.then(undefined, failCallback);
  }
  finally(callback) {
    this.then(
      (value) => {
        return MyPromise.resolve(callback()).then(() => value);
      },
      (e) => {
        return MyPromise.resolve(callback()).then(() => {
          throw this.reason;
        });
      }
    );
  }
  static resolve(value) {
    if (value instanceof MyPromise) return value;
    return new MyPromise((resolve) => resolve(value));
  }
  static reject(reason) {
    if (reason instanceof MyPromise) return reason;
    return new MyPromise((resolve, reject) => reject(reason));
  }
  static all(array) {
    let result = [];
    let index = 0;
    return new MyPromise((resolve, reject) => {
      function addData(key, value) {
        result[key] = value;
        index++;
        if (index === array.length) {
          resolve(result);
        }
      }
      for (const [key, current] of array.entries()) {
        if (current instanceof MyPromise) {
          current.then((value) => addData(key, value), reject);
        } else {
          addData(key, current);
        }
      }
    });
  }
  static race(array) {
    return new MyPromise((resolve, reject) => {
      let current;
      while ((current = array.shift())) {
        if (current instanceof MyPromise) {
          current.then(resolve, reject);
        } else {
          resolve(current);
        }
      }
    });
  }
}
function resolvePromise(promise, x, resolve, reject) {
  if (promise === x) {
    reject(new TypeError('Chaining cycle detected for promise #<Promise>'));
    return;
  }
  if (x instanceof MyPromise) {
    x.then(resolve, reject);
  } else {
    resolve(x);
  }
}
const p = new MyPromise((resolve, reject) => {
  setTimeout(() => {
    resolve(123);
  });
  // resolve(123);
});

p.then((res) => {
  console.log(res);
});

p.then((res) => {
  console.log(res);
});

p.then((res) => {
  console.log(res);
});

console.log('outer');

function p1() {
  return new MyPromise((resolve, reject) => {
    setTimeout(() => {
      reject('p1');
    }, 2000);
  });
}
function p2() {
  return new MyPromise((resolve, reject) => {
    setTimeout(() => {
      reject('p2');
    }, 2000);
  });
}

MyPromise.all(['a', 'b', p1(), p2(), 'c']).then(
  (result) => {
    console.log(result);
  },
  (e) => {
    console.log('MyPromise error: ', e);
  }
);

MyPromise.race([p2(), p1()]).then(
  (result) => {
    console.log('Promise result: ', result);
  },
  (e) => {
    console.log('Promise error: ', e);
  }
);
